﻿// Sequin.WebLogs.IO.ApacheLogReader
//
// (c) 2011 Arthur Pitman
//
// Part of the Sequin Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License (Version 2.1) as published by the Free Software Foundation.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License (Version 2.1) along with this library; if not, write to the 
// Free Software Foundation, Inc., 
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
// or see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Sequin.WebLogs.IO
{
    /// <summary>
    /// Reads an Apache web server log file
    /// </summary>
    public class ApacheLogReader : LogReader
    {        
        /// <summary>
        /// number of elements in an apache line
        /// </summary>
        protected const int elementCount = 10;

        /// <summary>
        /// Timestamp suffix splitter
        /// </summary>
        protected static char[] suffixSplitter = new char[] { '+', '-' };

        /// <summary>
        /// Space splitter
        /// </summary>
        protected static char[] spaceSplitter = new char[] { ' ' };

        /// <summary>
        /// Initializes a new <see cref="ApacheLogReader"/> instance with file or files specified by path parameter
        /// </summary>
        /// <param name="path">The location of file or files</param>
        public ApacheLogReader(string path)
            : base(path)
        {
        }

        /// <summary>
        /// Reads a <see cref="LogEntry"/>
        /// </summary>
        /// <returns>The <see cref="LogEntry"/> or null if none is available</returns>
        public override LogEntry ReadLogEntry()
        {
            // if possible, get the next line from the underlying reader
            var line = ReadLine();
            if (line == null)
                return null;

            var elements = SplitLine(line);

            // further divide the request itself
            var requestElements = elements[4].Split(spaceSplitter);

            // create new LogEntry
            return new LogEntry(                
                ParseApacheDateTimeString(elements[3]), // time stamp
                LogEntry.GetRequestType(requestElements[0].ToLower()), // request method
                requestElements[1], // request
                int.Parse(elements[5]), // response code
                elements[7], // referrer 
                new UserIdentity(
                    IPAddress.Parse(elements[0]), // IP
                    UserIdentity.MapUserAgentToId(elements[8].Replace(' ', '_').ToLower()))   // agent
                );
        }

        /// <summary>
        /// Splits an Apache line into elements, separated by space, or enclosed by [] or ""
        /// </summary>
        /// <param name="line">line to split</param>
        /// <returns>an array of elements</returns>
        protected string[] SplitLine(string line)
        {
            
            // start at the beginning of the line
            int chIndex = 0;

            var elements = new string[elementCount];
            for (int elementIndex = 0; elementIndex < elementCount; elementIndex++)
            {
                // skip whitespace
                while ((chIndex < line.Length) && char.IsWhiteSpace(line[chIndex]))
                    chIndex++;

                // if the end of the line has been hit, stop
                if (chIndex >= line.Length)
                    break;

                // get first character
                char ch = line[chIndex];

                // handle special elements, i.e. [ and ", which should be read until their matching ] and "
                if (ch == '[')
                {
                    chIndex++;
                    int startIndex = chIndex;
                    while ((chIndex < line.Length) && (line[chIndex] != ']'))
                        chIndex++;
                    elements[elementIndex] = line.Substring(startIndex, chIndex - startIndex);
                    chIndex++;
                }
                else if (ch == '\"')
                {
                    chIndex++;
                    int startIndex = chIndex;
                    bool escape = false;
                    while ((chIndex < line.Length) && (escape || (line[chIndex] != '\"')))
                    {
                        // next character is escaped if this character isnt escaped and is the escape character :S
                        escape = !escape && (line[chIndex] == '\\');
                        chIndex++;
                    }
                    elements[elementIndex] = line.Substring(startIndex, chIndex - startIndex);
                    chIndex++;
                }
                else
                {
                    int startIndex = chIndex;
                    while ((chIndex < line.Length) && (line[chIndex] != ' '))
                        chIndex++;
                    elements[elementIndex] = line.Substring(startIndex, chIndex - startIndex);
                }            
            }
            return elements;
        }


        /// <summary>
        /// Parses an Apache date and time string
        /// </summary>
        /// <param name="dateTimeString">the string to parse</param>
        /// <returns>The <see cref="DateTime"/></returns>
        protected DateTime ParseApacheDateTimeString(string dateTimeString)
        {
            TimeSpan timestampOffset = new TimeSpan(0);

            // look for a suffix that indicates an offset for the timestamp
            int suffixIndex = dateTimeString.IndexOfAny(suffixSplitter);
            if (suffixIndex >= 0)
            {
                string suffix = dateTimeString.Substring(suffixIndex).Trim();
                suffix = suffix.Substring(0, 3) + ":" + suffix.Substring(3);
                if (suffix[0] == '+')
                    suffix = suffix.Substring(1);
                timestampOffset = TimeSpan.Parse(suffix);

                dateTimeString = dateTimeString.Substring(0, suffixIndex).Trim();
                int firstColonIndex = dateTimeString.IndexOf(':');
                dateTimeString = dateTimeString.Substring(0, firstColonIndex) + " " + dateTimeString.Substring(firstColonIndex + 1);
            }

            return DateTime.Parse(dateTimeString) - timestampOffset;
        }
    }
}
